package com.ruoyi.common.validator;

import com.ruoyi.common.annotation.TruncateSize;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.*;
import java.lang.reflect.Field;
import java.util.Objects;

public class TruncateSizeValidator implements ConstraintValidator<TruncateSize, String> {

    private int max;

    @Override
    public void initialize(TruncateSize constraintAnnotation) {
        this.max = constraintAnnotation.max();
    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if (value == null || value.length() <= max) {
            return true; // 字符串长度符合要求
        }
        return false;

/*        // 获取当前验证的对象实例
        Object validatedObject = context.unwrap(javax.validation.ValidationContext.class)
                .getBeanInstance();

        // 获取被验证的字段名称
        String propertyName = ((javax.validation.Path.Node) context.getConstraintDescriptor().getValidationAppliesTo()).getName();

        try {
            // 使用反射获取字段对象
            Field field = validatedObject.getClass().getDeclaredField(propertyName);
            field.setAccessible(true);

            // 截断字符串并设置新值
            String truncatedValue = value.substring(0, max);
            field.set(validatedObject, truncatedValue);

            // 构建自定义消息
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("String has been truncated to " + max + " characters")
                    .addConstraintViolation();

            // 返回 false 表示验证失败（即触发了截断）
            return false;
        } catch (NoSuchFieldException | IllegalAccessException e) {
            throw new RuntimeException("Error accessing or modifying the field.", e);
        }*/
    }
}
